﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Aeon.Presentation.Dialogs
{
    /// <summary>
    /// Interaction logic for AudioBufferWindow.xaml
    /// </summary>
    public partial class AudioBufferWindow : Window
    {
        private GetPositions getPositions;
        private DispatcherTimer timer;
        private double bufferSize;

        /// <summary>
        /// Initializes a new instance of the AudioBufferWindow class.
        /// </summary>
        public AudioBufferWindow()
        {
            InitializeComponent();
        }

        public delegate void GetPositions(out int writePos, out int playPos);

        public void Attach(GetPositions getPositions, int bufferSize)
        {
            this.getPositions = getPositions;
            this.bufferSize = bufferSize;
            this.timer.Start();
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            this.timer = new DispatcherTimer(TimeSpan.FromSeconds(1.0 / 30.0), DispatcherPriority.Normal, UpdateDisplay, this.Dispatcher);
        }

        private void DisplayPositions(double writePos, double playPos)
        {
            double size = this.containerGrid.ActualWidth;
            this.writeIndicator.Margin = new Thickness(writePos * size, 0, 0, 0);
            this.playIndicator.Margin = new Thickness(playPos * size, 0, 0, 0);
        }

        private void UpdateDisplay(object sender, EventArgs e)
        {
            if(this.getPositions == null)
                return;

            int write;
            int play;
            this.getPositions(out write, out play);
            DisplayPositions((double)write / this.bufferSize, (double)play / this.bufferSize);
        }
    }
}
